package deep.projects.newsapp.adapters;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;

import java.util.ArrayList;
import deep.projects.newsapp.fragments.NewsPageFragment;

/**
 * NewsFragmentPagerAdapter 类为多个 NewsFragment 的数据适配器
 * Created by 吾心无待 on 2015/11/8.
 */
public class NewsFragmentPagerAdapter extends FragmentPagerAdapter{
    private FragmentManager mFragmentManager;
    private ArrayList<NewsPageFragment> mFragments;

    /**
     * 公有构造函数，初始化 NewsFragmentPagerAdapter 类的一个新实例
     * @param fm
     */
    public NewsFragmentPagerAdapter(FragmentManager fm) {
        super(fm);
        this.mFragmentManager = fm;
    }

    /**
     * 公有构造函数，初始化 NewsFragmentPagerAdapter 类的一个新实例
     * @param fm
     * @param fragments
     */
    public NewsFragmentPagerAdapter(FragmentManager fm,ArrayList<NewsPageFragment> fragments){
        super(fm);
        this.mFragmentManager = fm;
        this.mFragments = fragments;
    }

    @Override
    public Fragment getItem(int position) {
        return mFragments.get(position);
    }

    @Override
    public int getCount() {
        return mFragments.size();
    }

    /**
     *  设置分页器的 Fragment 列表
     * @param fragments
     */
    public void setFragments(ArrayList<NewsPageFragment> fragments) {
        if (mFragments != null) {
            FragmentTransaction ft = mFragmentManager.beginTransaction();
            for (Fragment f : this.mFragments) {
                ft.remove(f);
            }
            ft.commit();
            mFragmentManager.executePendingTransactions();
        }
        this.mFragments = fragments;
        notifyDataSetChanged();
    }


    @Override
    public CharSequence getPageTitle(int position) {
        return mFragments.get(position).getNewsType().getName();
    }
}
